package org.framework.lazy.cloud.network.heartbeat.protocol.socket5;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class Socks5ServerConnectHandler extends SimpleChannelInboundHandler<Object> {
    private final Channel relayChannel;

    public Socks5ServerConnectHandler(Channel relayChannel) {
        this.relayChannel = relayChannel;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        relayChannel.writeAndFlush(msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.read();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (relayChannel.isActive()) {
            relayChannel.writeAndFlush(new io.netty.handler.codec.socksx.v5.DefaultSocks5CommandResponse(
                            io.netty.handler.codec.socksx.v5.Socks5CommandStatus.FAILURE,
                            io.netty.handler.codec.socksx.v5.Socks5AddressType.IPv4))
                    .addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}    